import contextlib

from aiogram import types
from aiogram_dialog import DialogManager, StartMode

from dc_shop.core.exceptions.user import UserCartAlreadyExist, UserTgIdNotExist
from dc_shop.database.services.statistics import StatsService
from dc_shop.database.services.user import UserService
from dc_shop.tg_bot.states import ClientSG


async def user_start(
    message: types.Message | types.CallbackQuery,
    dialog_manager: DialogManager,
    user_service: UserService,
    stats_service: StatsService,
):
    """Команда старта для пользователей"""

    user_id = message.from_user.id
    username = message.from_user.username
    if not username:
        username = message.from_user.first_name

    try:
        await user_service.get_user_by_telegram_id(user_id)
    except UserTgIdNotExist:
        await user_service.create_user(
            telegram_id=user_id,
            username=username,
        )
        await stats_service.add_stats(users_registered=1)

    with contextlib.suppress(UserCartAlreadyExist):
        await user_service.create_user_cart(user_id)

    user = await user_service.get_user_by_telegram_id(user_id)

    if isinstance(message, types.CallbackQuery):
        await message.message.delete()
    if not user.is_adult:
        await dialog_manager.start(ClientSG.verify_age, mode=StartMode.RESET_STACK)
    elif not user.delivery_zone_id:
        await dialog_manager.start(ClientSG.select_delivery_zone, mode=StartMode.RESET_STACK)
    else:
        await dialog_manager.start(ClientSG.start, mode=StartMode.RESET_STACK)
